package com.czmh.etc.onlinepubsys.controller.wj;


import com.alibaba.fastjson.JSON;
import com.czmh.etc.common.core.utils.Base64ImageUtil;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.configuration.WxAppletConfig;
import com.czmh.etc.onlinepubsys.constants.wj.BusinessType;
import com.czmh.etc.onlinepubsys.entity.wj.CarInfo;
import com.czmh.etc.onlinepubsys.entity.wj.CurrentContext;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.entity.wj.EtcWjOrder;
import com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.request.wj.*;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.wj.WjIEtcOrderService;
import com.czmh.etc.onlinepubsys.services.wj.WjICurrentContextService;
import com.czmh.etc.onlinepubsys.utils.ImageZipUtil;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.wj.WjHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;


import java.util.Date;

/**
 * @author lyk
 * @since 2024-04-02
 */
@Slf4j
@RestController
@RequestMapping("/{version}/api/wj/order")
@Api(tags = "ETC订单接口【新】- 万集")
public class WjOrderController {

    @Autowired
    private WxAppletConfig config;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WjICurrentContextService currentContextService;

    @Autowired
    private EtcPayOrderService etcPayOrderService;

    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;

    @Autowired
    private WjIEtcOrderService wjEtcOrderService;

    @PostMapping("/checkCarPower")
    @ApiOperation("检查车辆是否可以办理接口 *新办流程")
    public JSONResult checkCarPower(@RequestBody checkCarPowerRequest req) {
        log.info("checkCarPower:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        ApiResponse r = WjHttpUtil.get(BusinessType.CHECK_CAR_POWER, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/create_InternalOrder")
    @ApiOperation("创建内部订单 *新办流程")
    public JSONResult create_InternalOrder(@RequestBody EtcWjOrder entity) {
        log.info("创建内部订单:{}", JSON.toJSONString(entity));

        // 手机号+验证码登录
        String redisValidCode = String.valueOf(redisUtil.get(entity.getPhoneNo()));
        if (StringUtils.isNotEmpty(entity.getValidCode()) && StringUtils.isNotEmpty(redisValidCode)
                && (entity.getValidCode().equals(redisValidCode))) {
            if ((redisUtil.get("unCheckPhoneList") != null ? String.valueOf(redisUtil.get("unCheckPhoneList")) : "").indexOf(entity.getPhoneNo()) == -1) {
                // 注销验证码
                redisUtil.del(entity.getPhoneNo());
            }
        } else {
            JSONResult result = new JSONResult();
            result.setCode(JSONResult.FAIL);
            result.setMessage("手机验证码不正确！");
            return result;
        }

        JSONResult result = new JSONResult();

        //如果用户存在且手机号码跟收货手机号码不同则根据收货手机号码创建新用户信息
        EtcUser e = etcUserInfoSevice.queryUserInfo(entity.getUserId());
        if (null == e) {
            EtcUser user = new EtcUser();
            user.setUser_id(Sequence.getId());
            user.setCreate_time(new Date());
            user.setUpdate_time(new Date());
            user.setUser_sex(1);
            user.setUser_status(0);
            // 1.初始化ETC用户信息
            etcUserInfoSevice.insert(user);
        } else if (StringUtils.isNotEmpty(e.getUser_phone()) && !e.getUser_phone().equalsIgnoreCase(entity.getPhoneNo())) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("该手机号码已经绑定其他ETC！");
            return result;
        }

        String userId = entity.getUserId();

        CurrentContext ctx = currentContextService.getByUserId(userId);

        if (ctx != null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("请先激活之前申请的设备");
            return result;
        }
        log.info("保存订单:{}", entity.getOrderNo());
        //记录当前进行时信息
        int payState = 0; //默认是未付款

        entity.setPayState(payState);

        ctx = new CurrentContext();
        ctx.setUserId(userId);
        ctx.setOrderNo(entity.getOrderNo());
        ctx.setState(payState);
        wjEtcOrderService.saveOrderAndContext(entity, ctx, null);

        return result;
    }

    @PostMapping("/createOrder")
    @ApiOperation("创建ETC订单接口 *新办流程")
    public JSONResult createOrder(@RequestBody createOrderRequest req) {
        log.info("创建ETC订单接口:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("暂无订单，请稍后再试！");
            return result;
        }
        ApiResponse r = WjHttpUtil.get(BusinessType.CREATE_ORDER, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/uploadImage")
    @ApiOperation("上传图片接口 *新办流程")
    public JSONResult uploadImage(@RequestBody uploadImageRequest req) throws Exception {
        log.info("上传图片接口:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        // 对Base64编码后的字符串进行SHA1散列
        String sha1Hash = Base64ImageUtil.hashWithSHA1(ImageZipUtil.handleAndReduceBase64(req.getFile()));
        req.setFile(ImageZipUtil.handleAndReduceBase64(req.getFile()));
        req.setImageDigest(sha1Hash);
        ApiResponse r = WjHttpUtil.post(BusinessType.UPLOAD_IMAG, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/commitApply")
    @ApiOperation("提交ETC订单接口 *新办流程")
    public JSONResult commitApply(@RequestBody commitApplyRequest req) {
        log.info("提交订单接口:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("暂无订单，请稍后再试！");
            return result;
        }
        ApiResponse r = WjHttpUtil.get(BusinessType.COMMIT_APPLY, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/saveCarInfo")
    @ApiOperation("新增车辆信息")
    public JSONResult saveCarInfo(@RequestBody SaveCarInfoRequest req) {
        JSONResult result = new JSONResult();
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        //根据流程汽车信息id判断是调用ETC车辆信息新增入库还是更新入库
        if (StringUtils.isEmpty(currentContext.getCarId())) {
            CarInfo carInfo = SaveCarInfoRequest.convert(req);
            carInfo.setId(Sequence.getId());
//            carInfoService.save(carInfo);
        }
        return result;
    }

    @PostMapping("/queryOrderStatus")
    @ApiOperation("查询订单状态接口")
    public JSONResult queryOrderStatus(@RequestBody orderRequest req) {
        log.info("查询订单状态接口:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("暂无订单，请稍后再试！");
            return result;
        }
        ApiResponse r = WjHttpUtil.get(BusinessType.QUERY_ORDER_STATUS, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                String orderStatus = JSON.parseObject(r.getRspData()).getJSONObject("data").getString("status");
                ctx.setState(Integer.parseInt(orderStatus));
                currentContextService.update(ctx);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/orderCancel")
    @ApiOperation("取消新办订单接口")
    public JSONResult orderCancel(@RequestBody orderRequest req) {
        log.info("取消新办订单接口:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
        if (ctx == null) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("暂无订单，请稍后再试！");
            return result;
        }
        ApiResponse r = WjHttpUtil.get(BusinessType.ORDER_CANCEL, JSON.toJSONString(req));
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                ctx.setState(4);
                ctx.setDeleteFlag(1);
                currentContextService.update(ctx);
                EtcWjOrder etcOrder = wjEtcOrderService.queryByOrderNo(ctx.getOrderNo());
                EtcUser etcUser = etcUserInfoSevice.queryUserInfo(ctx.getUserId());
                log.info("万集取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(ctx));
                log.info("万集取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                log.info("万集取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                etcOrder.setPayState(3);
                wjEtcOrderService.updateByObject(etcOrder);
                etcUser.setUser_loginname("");
                etcUser.setUser_phone("");
                etcUserInfoSevice.updateUser(etcUser);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMessage() : "服务器开小差，请稍后再试！");
        }
        return result;
    }
}

